'''
Created on Jul 22, 2010

@author: behrooz
'''
from amscms.ams.models import AdLikeDislike, Ad, AdView, Advertizer
from amscms.dict.models import Term
from amscms.reports.reports import ChartType, render_to_chart
from datetime import datetime
from django.contrib.auth.decorators import login_required
from django.db.models.aggregates import Count
from django.http import HttpResponseRedirect
from django.utils.translation import ugettext as _
from amscms.core.utils import navigation

def can_view_report(request, user, extra={}):
    if user is None or user.is_anonymous():
        return False
    if user.is_staff or user.is_superuser:
        return True
    adid = extra.get('adid', None)
    if adid is None:
        return False
    if Ad.objects.owns(adid, user):
        return True
    return False

@login_required()
def tags_popular(request, period=None):
    if not can_view_report(request, request.user):
        return HttpResponseRedirect("/")
    tags = Term.objects.find_popular_terms(size=10, period=period)
    column_desc = {
        "term" : ("string", _("Tags")),
        "y" : ("number", _("Frequency"))
    }
    chart_desc = {
        "chartTitle": _("Popular Tags"),
        "hAxisTitle": _("Tags"),
        "vAxisTitle": _("Frequency"), 
        "chartType": ChartType.ColumnChart,
    }
    data = [{"term": t.term, "y": t.frequency} for t in tags]
    revdata = [{"term": t.term[::-1], "y": t.frequency} for t in tags]
    context = {"custom_report_template" : "custom_popular_tags.html"}
    return render_to_chart(request, column_desc, chart_desc, data, revdata, context)

@login_required()
def ad_like_dislike(request, id):
    if not can_view_report(request, request.user, {"adid" : id}):
        return HttpResponseRedirect("/")
    navigation.breadcrumb(request, 'report_ad_like_dislike', id)
    likes = AdLikeDislike.objects.count_likes(id)
    dislikes = AdLikeDislike.objects.count_dislikes(id)
    ad = Ad.objects.get_by_id(id)
    columns_desc = {
        "type": ("string", _("Type")),
        "y": ("number", _("Value"))
    }
    chart_desc = {
        "chartTitle": ad.title,
        "chartType": ChartType.PieChart,
    }
    data = [
        {"type": _("Thumbs Up"), "y": likes},
        {"type": _("Thumbs Down"), "y": dislikes},
    ]
    revdata = [
        {"type": _("Thumbs Up")[::-1], "y": likes},
        {"type": _("Thumbs Down")[::-1], "y": dislikes},
    ]
    return render_to_chart(request, columns_desc, chart_desc, data, revdata)

@login_required()
def ad_view_history(request, id):
    if not can_view_report(request, request.user, {"adid" : id}):
        return HttpResponseRedirect("/")
    navigation.breadcrumb(request, 'report_ad_view_history', id)
    ad = Ad.objects.get_by_id(id)
    select_data = {"d": """date_format(last_modified, '%%m/%%d/%%Y')"""}
    result = AdView.objects.extra(select=select_data).filter(ad__id__exact=id).values('d').annotate(count=Count("last_modified"))
    columns_desc = {
        "the_date": ("date", _("Date")),
        "y": ("number", _("View Count"))
    }
    chart_desc = {
        "chartTitle": _("View History") + " " + ad.title,
        "chartType": ChartType.AnnotatedTimeLine,
        "displayAnnotations": "true", 
    }
    data = [{"the_date": datetime.strptime(r["d"], "%m/%d/%Y"), "y": r["count"]} for r in result]
    revdata = data[:]
    return render_to_chart(request, columns_desc, chart_desc, data, revdata)

@login_required()
def advertizer_top_investors(request):
    if not can_view_report(request, request.user):
        return HttpResponseRedirect("/")
    investors = Advertizer.objects.find_top_investor_advertizers()
    columns_desc = {
        "advertizer": ("string", _("Advertizer")),
        "y": ("number", _("Amount")),
    }
    chart_desc = {
        "chartTitle": _("Top Investor Advertizers"),
        "chartType": ChartType.ColumnChart,
        "hAxisTitle": _("Advertizer"),
        "vAxisTitle": _("Value")
    }
    data = [{"advertizer": d["advertizer"].__unicode__(), "y": d["total"]} for d in investors]
    revdata = [{"advertizer": d["advertizer"].__unicode__()[::-1], "y": d["total"]} for d in investors]
    return render_to_chart(request, columns_desc, chart_desc, data, revdata)

@login_required()
def advertizer_top_registrars(request):
    if not can_view_report(request, request.user):
        return HttpResponseRedirect("/")
    registrars  = Advertizer.objects.find_top_registrar_advertizers()
    columns_desc = {
        "advertizer": ("string", _("Advertizer")),
        "y": ("number", _("Count"))
    }
    chart_desc = {
        "chartTitle": _("Top Registrar Advertizers"),
        "chartType": ChartType.ColumnChart,
        "hAxisTitle": _("Advertizer"),
        "vAxisTitle": _("Value")
    }
    data = [{"advertizer": d["advertizer"].__unicode__(), "y": d["total"]} for d in registrars]
    revdata = [{"advertizer": d["advertizer"].__unicode__()[::-1], "y": d["total"]} for d in registrars]
    return render_to_chart(request, columns_desc, chart_desc, data, revdata)
